<template>
  <div>
    <el-form :model="params" ref="ruleForm" label-position="right" size="small" label-width="110px" class="base-search-more">
      <el-row >
        <el-col :span="6" v-if="$store.state.showAgent">
          <el-form-item label="区域">
            <agent-list style="width: 100%" :agentids="params.agentIds" v-on:listenToChildEvent="getAentId"></agent-list>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商户名称">
            <el-input style="width: 100%" placeholder="请输入内容" v-model="params.name" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="用户号码">
            <el-input style="width: 100%" placeholder="请输入内容" v-model="params.usermobile" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="审核状态">
            <el-select style='width: 100%' v-model="params.status" clearable>
              <el-option label="待审核" value="0"></el-option>
              <el-option label="通过" value="1"></el-option>
              <el-option label="不通过" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="处理状态">
            <el-select style='width: 100%' v-model="params.state" size="small">
              <el-option label="已处理" value="1"></el-option>
              <el-option label="未处理" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="日期">
            <pt-date-picker v-model="params.date" :shortcuts="[{ text: '今天', start: 0, end: 0}, { text: '近七天', start: -7, end: 0}, {text: '近一个月', start: -30, end: 0}]" />
          </el-form-item>
        </el-col>
        <el-col :span="$store.state.showAgent ? 12 : 18" style="text-align: right;">
          <el-form-item label-width="0">
            <el-button @click="exportExcel()" v-loading="ExcelLoading">导出表格<i class="el-icon-download"></i></el-button>
            <el-button type="primary" icon="el-icon-search" @click="$refs.pagination.handleSizeChange(10)">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="base-table-wrap">
      <el-row style="text-align: right;">
        <el-button @click="changeOpr(1)" type="primary">批申请通过</el-button>
        <el-button @click="changeOpr(2)" type="warning">批申请驳回</el-button>
        <el-button @click="changeOpr(3)" type="primary" plain>批处理完成</el-button>
      </el-row>
      <el-table :data="tableData.rows" style="width: 100%; margin-top: 20px" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="商家或商户">
                <span>{{ props.row.username }}</span>
              </el-form-item>
              <el-form-item label="联系电话">
                <span>{{ props.row.usermobile }}</span>
              </el-form-item>
               <el-form-item label="所属区域">
                <span>{{ props.row.agentname }}</span>
              </el-form-item>
              <el-form-item label="申请时间">
                <span>{{ props.row.createtime }}</span>
              </el-form-item>
              <el-form-item label="提现账号">
                <span>{{ props.row.account }}</span>
              </el-form-item>
              <el-form-item label="提现金额">
                <span>{{ props.row.monetary }}</span>
              </el-form-item>
              <el-form-item label="银行类型">
                <span>{{ props.row.banktype }}</span>
              </el-form-item>
               <el-form-item label="时间跨度">
                <span>{{ props.row.wdate }}</span>
              </el-form-item>
               <el-form-item label="开户人">
                <span>{{ props.row.name }}</span>
              </el-form-item>
              <el-form-item label="审核状态">
                <span v-if="props.row.state=='1'">已完成</span>
                <span v-else>{{props.row.status===0?'待审核':props.row.status===1?'申请通过': props.row.status===2 ?'被驳回' : ''}}</span>
              </el-form-item>         
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="id" width="0" v-if="show" align="center"></el-table-column>
        <el-table-column prop="username" label="商家或商户" min-width="130" align="center"></el-table-column>
        <el-table-column prop="usermobile" label="号码" min-width="120" align="center"></el-table-column>
        <el-table-column prop="monetary" label="金额" min-width="120" align="center"></el-table-column>
        <el-table-column prop="agentname" label="区域名称" min-width="120" align="center"></el-table-column>
        <el-table-column prop="createtime" label="申请时间" min-width="140" align="center"></el-table-column>
        <el-table-column prop="status" label="申请进度" min-width="100" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.state=='1'">已完成</span>
            <span v-else>{{scope.row.status=== 0 ?'待审核':scope.row.status=== 1?'申请通过': scope.row.status===2 ?'被驳回' : ''}}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="140" align="right">
          <template slot-scope="scope">
            <el-button v-if="scope.row.status=='1' && scope.row.state === 0" type="text" style="color: red"
                         @click.native.prevent="onChange(scope.row.id, 0)">反审核</el-button>
            <el-button v-if="scope.row.status === 0 && scope.row.state === 0" type="text" style="color: #1ac423"
                          @click.native.prevent="onChange(scope.row.id, 1)">申请通过</el-button>
            <el-button v-if="scope.row.status === 0 && scope.row.state === 0" type="text" style="color: red"
                          @click.native.prevent="openRemarks(scope.row.id)">申请驳回</el-button>
            <el-tooltip v-if="scope.row.status === 1 && scope.row.state === 0" 
              :disabled="scope.row.isWeiXin !== 0" 
              content="未开通" placement="top" effect="dark">
              <el-button v-if="scope.row.isWeiXin === 0" style="color: #c0c4cc; cursor: not-allowed;" type="text">微信</el-button>
              <el-button v-else type="text" @click.native.prevent="setComplateOhter(scope.row.id, 2)">微信</el-button>
            </el-tooltip>
              <el-tooltip v-if="scope.row.status === 1 && scope.row.state === 0" 
                :disabled="scope.row.isZfb !== 0"
                content="未开通" placement="top" effect="dark">
              <el-button v-if="scope.row.isZfb === 0"
                type="text" style="color: #c0c4cc; cursor: not-allowed;">支付宝</el-button>
              <el-button v-else type="text" @click.native.prevent="setComplateOhter(scope.row.id, 1)">支付宝</el-button>
            </el-tooltip>
            <el-button v-if="scope.row.status === 1 && scope.row.state === 0" 
              type="text" @click.native.prevent="setComplate(scope.row.id)">处理完成</el-button>
              <div style="text-align:left;" v-if="scope.row.state=== 0 && scope.row.status === 2">
                <strong>【驳回理由】</strong>{{scope.row.examine_remarks}}</div>
          </template>
        </el-table-column>
      </el-table>
      <pt-table-loading v-show="isloadingTable"></pt-table-loading>
      <pt-pagination ref="pagination" :total="tableData.total" @listeningEvent="triggerEvent"></pt-pagination>
    </div>
    <el-table v-show="false" :data="ExTableData" :summary-method="getSummaries" show-summary id="out-table" >  <!--不显示的表格下载-->
      <el-table-column prop="username" label="商家或商户" min-width="130" align="center"></el-table-column>
      <!--<el-table-column prop="cuserId" label="商家或商户" min-width="130" align="center"></el-table-column>-->
      <el-table-column prop="usermobile" label="号码" min-width="120" align="center"></el-table-column>
      <el-table-column prop="monetary" label="金额" min-width="120" align="center"></el-table-column>
      <el-table-column prop="agentname" label="区域名称" min-width="120" align="center"></el-table-column>
      <el-table-column prop="createtime" label="申请时间" min-width="140" align="center"></el-table-column>
      <el-table-column prop="status" label="申请进度" min-width="100" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.state=='1'">已完成</span>
          <span v-else>{{scope.row.status=='0'&&scope.row.state=='1'?'待审核':scope.row.status=='1'?'申请通过':'申请未通过'}}</span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
  import FileSaver from 'file-saver'
  import XLSX from 'xlsx'
  import acction from '@/utils/acction.js'
  import { getDay } from '@/utils/ptkc.js'
  export default {
    data() {
      return {
        show: false,
        examine: false, // 审核
        params: { // 查询数据
          page: 0,
          size: 10,
          name: '',
          state: '',
          status: '',
          usermobile: '',
          date: [getDay(-30) + ' ' + '00:00:00', getDay(0) + ' ' + '23:59:59'],
          agentIds: []
        },
        list: [],
        isloadingTable: false,
        ExcelLoading: false,
        ExTableData: [], //表格数据
        tableData: {}, //表单数据
        multipleSelection: []
      }
    },
    methods: {
      handleSelectionChange(val) {
        this.multipleSelection = val
        this.list = []
        this.multipleSelection.forEach((item) => {
          this.list.push(item)
        })
      },
      changeOpr(type) {
        if (this.list.length == 0) {
          this.$message.error('请至少选择一项！')
          return false
        }
        let issure = true
        if(type == 1 || type == 2){
          this.list.forEach((item,index)=>{
            if(item.state == '1'){
              this.$message.error('当前选项中存在已完成申请！')
              issure = false
              return false
            }
          })
        }
        if(type ==3){
          this.list.forEach((item,index)=>{
            if(item.stauts != '1'){
              this.$message.error('当前选项中存在未通过的申请！')
              issure = false
              return false
            }
          })
        }
        if(issure){
          let ids = []
          this.list.forEach((item) =>{ids.push(item.id)})
          let params = {opr: type, ids}
          params.ids = params.ids.length > 0 ? params.ids.join(',') : ''
          this.isloadingTable = true
          this.$http.get('/server/business/batchAudit?' + this.qs.stringify(params)).then(res => {
            this.isloadingTable = false
            if (res.data.success) {
              this.$message.success('操作完成！')
              this.getTableList()
            }
          })
          .catch(err => {
            this.isloadingTable = false
          })
        }
      },
      getAentId(item) {  //获取子组件传递的区域
        this.params.agentIds = item
      },
      getSummaries(param) { // 表格统计
        const {columns, data} = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总计'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return new acction(prev,curr).accAdd()
              } else {
                return prev
              }
            }, 0)
            //sums[index] += ' 元';
          } else {
            sums[index] = 'N/A'
          }
        })
        return sums
      },
      exportExcel() { // 导出表格
        this.ExcelLoading = true
        const params = { ...this.params }
        params.createtime1 = params.date?params.date[0] : ''
        params.createtime2 = params.date?params.date[1] : ''
        params.agentIds = params.agentIds.length > 0 ? params.agentIds.join(',') : ''
        params.page = 0
        params.size = this.total
        delete params.date
        this.$http.get('/server/business/moneyhome?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.ExTableData = res.data.data.rows
            setTimeout(() => {
              var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
              var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'})
              try {
                FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), `${params.createtime1.slice(0,10)}-${params.createtime2.slice(0,10)}.xls`)
              } catch (e) {
              }
              return wbout
            }, 500)
          }
        }).finally(() => { this.ExcelLoading = false })
      },
      triggerEvent(type,val) { // 分页器
        if (type === 'page') {
          this.params.page = val - 1
        } else if (type === 'size') {
          this.params.page = 0
          this.params.size = val
        }
        this.getTableList()
      },
      getTableList() {
        const params = { ...this.params }
        params.createtime1 = params.date ? params.date[0] : ''
        params.createtime2 = params.date ? params.date[1] : ''
        delete params.date
        params.agentIds = params.agentIds.length > 0 ? params.agentIds.join(',') : ''
        this.isloadingTable = true
        this.$http.get('/server/business/moneyhome?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.total = res.data.data.total
            this.tableData = res.data.data
          }
        }).finally(() => { this.isloadingTable = false })
      },
      openRemarks(id) { // 驳回理由弹窗
        this.$prompt('请输入驳回理由', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[^\s]{0,30}$/,
          inputErrorMessage: '文本超出限制'
        }).then(({ value }) => {
          this.onChange(id, 2, value)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });       
        });
      },
      onChange(id, status, remarks) { // 改变审核状态
        const params = {id, status, remarks}
        this.isloadingTable = true
        this.$http.get('/server/business/applicationPassed?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.$message.success('操作成功')
            this.params.createtime1 = this.params.date[0]
            this.params.createtime2 = this.params.date[1]
            this.getTableList()
          }
        }).finally(() => { this.isloadingTable = false })
      },
      setComplate(id) { // 处理完成
        let params = {id, state: 1}
        this.isloadingTable = true
        this.$http.get('/server/business/applicationProcessing?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.$message.success('操作成功')
            this.params.createtime1 = this.params.date[0]
            this.params.createtime2 = this.params.date[1]
            this.getTableList()
          }
        }).finally(() => { this.isloadingTable = false })
      },
      setComplateOhter(id, paytype) { // 支付宝或微信
        const params = {id, paytype}
        this.isloadingTable = true
        this.$http.get('/server/business/payToBusiness?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.$message.success('操作成功')
            this.params.createtime1 = this.params.date[0]
            this.params.createtime2 = this.params.date[1]
            this.getTableList()
          }
        }).finally(() => { this.isloadingTable = false })
      }
     
    },
    mounted() {
      this.getTableList()
    }
  }
</script>

<style scoped>
  .header {
    padding: 15px 15px 0 15px;
    background: #fff;
    border-bottom: 1px solid #e5e5e5;
  }

  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
